package user;

import cn.bm.web.services.UserServices;
import spark.Route;
import spark.Session;

import static spark.Spark.*;

// req 封装 servlet
public class UserController {
    static Route login = (req,res)->{
        // 设置session
        String username = req.queryParams("username");
        String password = req.queryParams("password");
        Boolean loginSuccessful = UserServices.login(username,password);
        System.out.println("logined:"+loginSuccessful);
        if(loginSuccessful){
            System.out.println("登录成功！");
            Session session = req.session(true); // 获取当前会话，如果不存在则创建一个新的
            session.attribute("username", username);// 将用户名存储在会话中
            res.redirect("/login.html");
        }else {
            //req.session().attribute("username","lys");;
            System.out.println("登录失败！");
        }

        return "login";
    };

    static Route register = (req,res)->{
        String username = req.queryParams("username");
        String password = req.queryParams("password");
        Boolean registerSuccessful = UserServices.register(username,password);
        System.out.println("logined:"+registerSuccessful);
        if(registerSuccessful){
            System.out.println("注册成功！");
            Session session = req.session(true); // 获取当前会话，如果不存在则创建一个新的
            session.attribute("username", username);// 将用户名存储在会话中
            res.redirect("/index.html");
        }else {
            //req.session().attribute("username","lys");;
            System.out.println("注册失败！");
            res.redirect("/register.html");
        }

        return "register";
    };

    static Route test =(req,res)->{
        System.out.println(req.ip());

        req.session().attribute("user","none");

        return "test";

    };
    static Route test1 =(req,res)->{
        System.out.println(req.ip());

        req.session().attribute("user","none");

        return "testauth";

    };



    public static void InitRoutes() {

        /**
         * 开放访问
         */
        System.out.println("init user controller");

        get("/user/login",login);
        post("/user/login",login);
        post("/user/register",register);
        /**
         * 授权后访问
         */
        get("/app/test",test);
        get("/auth/test",test1);
    }
}

